﻿package idv.cjcat.emitter {
	use namespace engine;
	
	
	/**
	 * Common math functions.
	 */
	public class EmitterMath {
		
		/**
		 * Clamps a value within bounds.
		 * @param	input
		 * @param	lowerBound
		 * @param	upperBound
		 * @return
		 */
		public static function clamp(input:Number, lowerBound:Number, upperBound:Number):Number {
			if (input < lowerBound) return lowerBound;
			if (input > upperBound) return upperBound;
			return input;
		}
		
		/**
		 * Interpolates linearly between two values.
		 * @param	x1
		 * @param	y1
		 * @param	x2
		 * @param	y2
		 * @param	x3
		 * @return
		 */
		public static function interpolate(x1:Number, y1:Number, x2:Number, y2:Number, x3:Number):Number {
			return y1 - ((y1 - y2) * (x1 - x3) / (x1 - x2));
		}
		
		/**
		 * Uniform sample.
		 * @param	mean
		 * @param	deviation
		 * @return
		 */
		public static function uniformSample(mean:Number, deviation:Number):Number {
			return mean + (Math.random() - 0.5) * deviation * 2;
		}
		
		/**
		 * Normal distribution.
		 * @param	mean
		 * @param	deviation
		 * @param	iterations
		 * @return
		 */
		public static function normalDistribution(mean:Number, deviation:Number, iterations:int = 3):Number {
			if (iterations <= 0) return mean;
			var temp:Number = 0;
			for (var i:int = 1; i <= iterations; i++) {
				temp += (Math.random() - 0.5) * deviation * 2;
			}
			temp /= iterations;
			temp += mean;
			return temp;
		}
		
		/**
		 * Probability Boolean.
		 * @param	p
		 * @return
		 */
		public static function prob(p:Number):Boolean {
			p = clamp(p, 0, 1);
			if (Math.random() <= p) return true;
			return false;
		}
	}
}